/**
 * Created by IntelliJ IDEA.
 * Time: 13:17
 *
 * @Author: xyb
 * @Version: 2017/7/7
 * To change this template use File | Settings | File Templates.
 */
package blog.sys.service;

import blog.sys.data.message.MsgIndexInfo;
import blog.sys.entity.ChatMsg;
import blog.sys.entity.User;
import blog.web.app.data.ClientInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pub.dao.GeneralDao;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(readOnly = true)
public class MessageService {


    /**
     * 获取用户的好友列表与他的最新聊天记录
     *
     * @param userId
     * @return
     * @throws UnsupportedEncodingException
     */
    public List<MsgIndexInfo> getUserFriends(Integer userId) throws UnsupportedEncodingException {
        String sql = "SELECT u.* from t_user u where u.id in (select f.fid from t_user_friend f where f.uid=? \n" +
                "UNION ALL \n" +
                "select f.uid from t_user_friend f where f.fid=?);";
        List<User> users = generalDao.queryList(User.class, sql, userId, userId);
        List<MsgIndexInfo> indexInfos = new ArrayList<>();
        MsgIndexInfo msg;
        for (int i = 0; i < users.size(); i++) {
            Integer toUserId = users.get(i).getId();
            String sql2 = "SELECT m.content FROM t_chat_msg m WHERE m.user_id= ? AND m.to_user_id = ? or m.to_user_id = ? AND m.user_id=? ORDER BY m.id desc LIMIT 1";
            msg = generalDao.queryValue(MsgIndexInfo.class, sql2, userId, toUserId, userId, toUserId);
            if (msg == null) {
                msg = new MsgIndexInfo();
            }
            msg.setUser(users.get(i));
            if (msg != null && msg.getContent() != null) {
                String con = URLDecoder.decode(msg.getContent(), "utf-8");
                msg.setContent(con);
            }
            indexInfos.add(msg);
        }
        return indexInfos;
    }

    /**
     * 获取与当前好友的聊天记录
     * 使用分页
     *
     * @param userId 当前用户id
     * @param toUserId 好友id
     * @param pageNum  显示当前页的聊天记录，默认是一页显示十条记录
     * @return
     * @throws UnsupportedEncodingException
     */
    public List<ChatMsg> onShowCurrChatMsg(Integer userId, Integer toUserId, Integer pageNum) throws UnsupportedEncodingException {
        Integer num = (pageNum - 1) * 10;
        String sql = "SELECT * FROM t_chat_msg m WHERE m.user_id= ? AND m.to_user_id = ? or m.to_user_id = ? AND m.user_id=? GROUP BY id ORDER BY m.id desc LIMIT ?, 10 ";
        List<ChatMsg> msgs = generalDao.queryList(ChatMsg.class, sql, userId, toUserId, userId, toUserId, num);
        for (ChatMsg msg : msgs) {
            String con = URLDecoder.decode(msg.getContent(), "utf-8");
            msg.setContent(con);
        }
        return msgs;
    }


    /**
     * 获取我所有未读信息
     *
     * @param userId
     * @return
     */
    public Integer getMsgNum(Integer userId) {
        String sql = "SELECT COUNT(*) FROM t_chat_msg where status = 0 AND to_user_id = ?";
        Integer count = generalDao.queryValue(Integer.class, sql, userId);
        return count;
    }

    /**
     * 更新已读的信息
     *
     * @param UserId
     */
    @Transactional
    public void onUpdateChatMsg(Integer UserId) {
//        Integer ToUserId = ClientInfo.getUserId();
//        String sql = "UPDATE t_chat_msg m SET m.status = 1 WHERE m.user_id = ? AND m.to_user_id =? AND m.status = 0";
//        generalDao.execute(sql, UserId, ToUserId);
    }

    @Autowired
    private GeneralDao generalDao;

}
